// pages/personal/address/address.js
const personal = require('../../../api/personal.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: [],
    userInfo: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  // 获取用户信息
  getUserInfo(token) {
    personal.getUserInfo(token).then(res => {
      if (res.data.code == 0) {
        this.setData({
          userInfo: res.data.data
        })
        let address = wx.getStorageSync('address' + this.data.userInfo.id) || []
        this.setData({
          address: address
        })
        wx.hideLoading()
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let token = wx.getStorageSync('token')
    this.getUserInfo(token)
    console.log(this.data.userInfo.id)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 选中地址
  select(e) {
    console.log(e)
    let address = wx.getStorageSync('address' + this.data.userInfo.id) || []
    address.forEach(value => {
      if(value.id == e.currentTarget.dataset.id) {
        value.isSelected = !value.isSelected
      }else {
        value.isSelected = false
      }
    })
    this.setData({
      address: address
    })
    wx.setStorageSync('address' + this.data.userInfo.id, address)
  },
  // 跳转新增地址
  addAddress() {
    wx.navigateTo({
      url: '../address/newaddress/newaddress',
    })
  },
  // 删除地址
  delAddress(e) {
    console.log(e)
    let that = this
    let address = wx.getStorageSync('address' + this.data.userInfo.id) || []
    console.log(address)
    wx.showModal({
      title: '确定删除？',
      success(res) {
        if(res.confirm) {
          address.forEach((value, index) => {
            console.log(index)
            if(value.id == e.currentTarget.dataset.id) {
              address.splice(index, 1)
            }
          })
          console.log(address)
          that.setData({
            address: address
          })
          wx.setStorageSync('address' + that.data.userInfo.id, address)
        }else if(res.cancel) {
          console.log('取消')
        }
      }
    })
  },
  // 跳转编辑
  editAddress(e) {
    let id = e.currentTarget.dataset.id
    wx.navigateTo({
      url: '../address/newaddress/newaddress?id=' + id,
    })
  }
})